package zxing.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.SongBean;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.http.HttpUtils;
import okhttp3.Request;
import okhttp3.Response;
import zxing.activity.adapter.MusicAdapter;

public class MusicListActivity extends VActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener {
    List<SongBean.DataBean> songBeans;
    private MediaPlayer mediaPlayer;
    @BindView(R.id.recy_list)
    RecyclerView recyList;
    private MusicAdapter adapter;
    @BindView(R.id.head_back)
    ImageView head_back;
    @BindView(R.id.head_center_title)
    TextView head_center_title;
    @BindView(R.id.head_right_title)
    TextView head_right_title;
    String voiceFilePath, voiceName;
    private boolean isPlay = true;
    int pos;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        getMusic();
        ButterKnife.bind(this);
        Intent intent = getIntent();
        pos = intent.getIntExtra("pos", 0);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyList.setLayoutManager(linearLayoutManager);
        head_center_title.setText("音乐列表");
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        head_right_title.setVisibility(View.VISIBLE);
        head_right_title.setText("确定");
        head_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                if (TextUtils.isEmpty(voiceFilePath)) {
                    intent.putExtra("voiceFilePath", songBeans.get(pos).getUrl());
                } else {
                    intent.putExtra("voiceFilePath", voiceFilePath);
                }
                if (TextUtils.isEmpty(voiceName)) {
                    intent.putExtra("voiceName", songBeans.get(pos).getName());
                } else {
                    intent.putExtra("voiceName", voiceName);
                }
                intent.putExtra("pos", pos);
                setResult(1, intent);
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release();
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void initDatas() {
        if (songBeans != null) {
            adapter = new MusicAdapter(MusicListActivity.this, songBeans);
            recyList.setAdapter(adapter);
            adapter.setsele(pos);
            initAction();
        }

    }

    private void getMusic() {
        HttpUtils.getInstance().postMusic(new BaseCallback<SongBean>() {
            @Override
            public void onRequestBefore() {
            }

            @Override
            public void onFailure(Request request, Exception e) {
            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onSuccess(Response response, SongBean o) {
                Log.e("TAG", o.toString());

                songBeans = o.getData();
                initDatas();
//                if (o != null && response.isSuccessful()) {
//                    if (DataSupport.findFirst(SongBean.class) != null) {
//                        DataSupport.deleteAll(SongBean.class);
//                    }
//                    o.save();
//                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

    protected void initAction() {
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter madapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.img_btn:  //播放暂停按钮
                        voiceFilePath = (String) view.getTag();
                        if (isPlay == true) {
                            adapter.setPlay(position, true);
                            isPlay = false;
                            mediaPlayerStart();
                        } else {
                            adapter.setPlay(position, false);
                            isPlay = true;
                            mediaPlayerStop();
                        }
                        break;
                    case R.id.item_parent://整个item
                        adapter.setsele(position);
                        voiceFilePath = (String) view.getTag();
                        voiceName = songBeans.get(position).getName();
                        pos = position;
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 播放音频文件
     */
    private void mediaPlayerStart() {
        mediaPlayer = MediaPlayer.create(this, Uri.parse(voiceFilePath));
        mediaPlayer.setOnCompletionListener(this);
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
    }

    /**
     * 取消播放音频文件
     */
    private void mediaPlayerStop() {
        if (mediaPlayer.isPlaying() || mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
//        mp.start();
    }

    @Override
    public void onClick(View v) {

    }
}
